import 'package:demo1/provider/category_goods_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:convert';
import '../service/service_method.dart';
import '../model/category.dart';
import '../model/category_goods_list.dart';
import '../provider/child_category.dart';
import '../provider/category_goods_list.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  var scrollController = new ScrollController();
  @override
  Widget build(BuildContext context) {
    try {
      if (Provider.of<ChildCategory>(context).page == 1) {
        // scrollController.jumpTo(0.0);
      }
    } catch (e) {
      print(e);
    }
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(primaryColor: Colors.pink),
        home: Scaffold(
            appBar: AppBar(title: Text('类别')),
            body: Container(
                child: Row(
              children: <Widget>[
                LeftCategoryNav(),
                Column(
                  children: <Widget>[RightCategoryNav(), CategoryGoodsList()],
                )
              ],
            ))));
  }
}

class LeftCategoryNav extends StatefulWidget {
  @override
  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List list = [];
  var listIndex = 0; // 大类索引

  @override
  void initState() {
    super.initState();
    _getCategory();
    _getGoodsList();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        width: ScreenUtil().setWidth(180),
        decoration: BoxDecoration(
            border:
                Border(right: BorderSide(width: 1.0, color: Colors.black12))),
        child: ListView.builder(
            itemCount: list.length,
            itemBuilder: (context, index) {
              return _leftInkWell(index);
            }));
  }

  Widget _leftInkWell(int index) {
    bool isClick = false;
    isClick = (index == listIndex) ? true : false;
    return InkWell(
        onTap: () {
          print('点击大分类');
          setState(() {
            listIndex = index;
          });
          var childList = list[index].bxMallSubDto;
          var categoryId = list[index].mallCategoryId;

          Provider.of<ChildCategory>(context, listen: false)
              .setChildCategory(childList, categoryId);
          _getGoodsList(categoryId: categoryId);
        },
        child: Container(
            height: ScreenUtil().setHeight(100),
            padding: EdgeInsets.only(left: 10, top: 20),
            decoration: BoxDecoration(
              color: isClick ? Colors.pink[400] : Colors.white,
              border:
                  Border(bottom: BorderSide(width: 1, color: Colors.black12)),
            ),
            alignment: Alignment.centerLeft,
            child: Text(
              list[index].mallCategoryName,
              style: TextStyle(
                  color: isClick ? Colors.white : Colors.black,
                  fontSize: ScreenUtil().setSp(28)),
            )));
  }

  void _getCategory() async {
    await request('getCategory').then((val) {
      var data = json.decode(val.toString());
      CategoryModel category = CategoryModel.fromJson(data);
      setState(() {
        list = category.data;
      });
      Provider.of<ChildCategory>(context, listen: false)
          .setChildCategory(list[0].bxMallSubDto, list[0].mallCategoryId);
    });
  }

  void _getGoodsList({String categoryId}) async {
    var postData = {
      'categoryId': categoryId == null ? '4' : categoryId,
      'categorySubId': '',
      'page': 1
    };
    var res = await request('getMallGoods', formData: postData);
    var data = json.decode(res.toString());
    CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
    Provider.of<CategoryGoodsListProvider>(context, listen: false)
        .setGoodsList(goodsList.data);
    // listen: false => read<>()  listen:true => watch<>()
    // context.read<CategoryGoodsListProvider>().setGoodsList(goodsList.data);
  }
}

class RightCategoryNav extends StatefulWidget {
  @override
  _RightCategoryNavState createState() => _RightCategoryNavState();
}

class _RightCategoryNavState extends State<RightCategoryNav> {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Container(
            height: ScreenUtil().setHeight(80),
            width: ScreenUtil().setWidth(570),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                    bottom: BorderSide(width: 1, color: Colors.black12))),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount:
                  context.watch<ChildCategory>().childCategoryList.length,
              itemBuilder: (context, index) {
                return _rightInkWell(
                    context.watch<ChildCategory>().childCategoryList[index],
                    index);
              },
            )));
  }

  Widget _rightInkWell(BxMallSubDto item, int index) {
    return InkWell(
        onTap: () {
          print('点击小类 ${item.mallSubName} ${item.mallSubId}');
          context.read<ChildCategory>().changeChildIndex(index, item.mallSubId);
          _getGoodsList(item.mallSubId);
        },
        child: Container(
            padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
            child: Text(item.mallSubName,
                style: TextStyle(fontSize: ScreenUtil().setSp(28)))));
  }

  void _getGoodsList(String categorySubId) async {
    var postData = {
      'categoryId':
          Provider.of<ChildCategory>(context, listen: false).categoryId,
      'categorySubId': categorySubId,
      'page': 1
    };
    var res = await request('getMallGoods', formData: postData);
    var data = json.decode(res.toString());
    CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
    if (goodsList.data == null) {
      Provider.of<CategoryGoodsListProvider>(context, listen: false)
          .setGoodsList([]);
    } else {
      Provider.of<CategoryGoodsListProvider>(context, listen: false)
          .setGoodsList(goodsList.data);
    }
  }
}

class CategoryGoodsList extends StatefulWidget {
  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {
  List list = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (context.watch<CategoryGoodsListProvider>().goodsList.length > 0) {
      return Expanded(
        child: Container(
            width: ScreenUtil().setWidth(570),
            child: EasyRefresh(
                child: ListView.builder(
                  itemBuilder: (context, index) {
                    return _listWidget(
                        context.watch<CategoryGoodsListProvider>().goodsList,
                        index);
                  },
                  itemCount: context
                      .watch<CategoryGoodsListProvider>()
                      .goodsList
                      .length,
                ),
                onLoad: () async {
                  print('没有更多数据了');
                  _getMoreList();
                })),
      );
    } else {
      return Text('暂无数据');
    }
  }

  Widget _goodsImage(List newList, int index) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(newList[index].image),
    );
  }

  Widget _goodsName(List newList, int index) {
    return Container(
        padding: EdgeInsets.all(5),
        width: ScreenUtil().setWidth(370),
        child: Text(
          newList[index].goodsName,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ));
  }

  Widget _goodsPrice(List newList, int index) {
    return Container(
        margin: EdgeInsets.only(top: 20),
        width: ScreenUtil().setWidth(370),
        child: Row(
          children: <Widget>[
            Text(
              '价格：￥${newList[index].presentPrice}',
              style: TextStyle(
                  color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
            ),
            Text('￥${newList[index].oriPrice}',
                style: TextStyle(
                    color: Colors.black26,
                    decoration: TextDecoration.lineThrough))
          ],
        ));
  }

  Widget _listWidget(List newList, int index) {
    return InkWell(
        onTap: () {},
        child: Container(
            padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
            decoration: BoxDecoration(
              color: Colors.white,
              border:
                  Border(bottom: BorderSide(width: 1.0, color: Colors.black12)),
            ),
            child: Row(
              children: <Widget>[
                _goodsImage(newList, index),
                Column(
                  children: <Widget>[
                    _goodsName(newList, index),
                    _goodsPrice(newList, index)
                  ],
                )
              ],
            )));
  }

  void _getMoreList() async {
    var postData = {
      'categoryId':
          Provider.of<ChildCategory>(context, listen: false).categoryId,
      'categorySubId': context.read<ChildCategory>().subId,
      'page': context.read<ChildCategory>().page,
    };
    var res = await request('getMallGoods', formData: postData);
    var data = json.decode(res.toString());
    CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
    if (goodsList.data == null) {
      Provider.of<CategoryGoodsListProvider>(context, listen: false)
          .setGoodsList([]);
    } else {
      Provider.of<CategoryGoodsListProvider>(context, listen: false)
          .setGoodsList(goodsList.data);
    }
  }
}
